package cz.ctu.android.DriveCommunicator.activities;

import java.util.ArrayList;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.ActivityNotFoundException;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.gesture.Gesture;
import android.gesture.GestureLibraries;
import android.gesture.GestureLibrary;
import android.gesture.GestureOverlayView;
import android.gesture.Prediction;
import android.gesture.GestureOverlayView.OnGesturePerformedListener;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.telephony.SmsManager;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import cz.ctu.android.DriveCommunicator.R;

/**
 *
 * @author Zdeny
 */
public class ReplyKeyboardActivity extends Activity implements OnGesturePerformedListener,OnInitListener {

    private String hintTxt = "Type your message here ...";
    private GestureLibrary mLibrary;
    private TextToSpeech tts;
    private int MY_DATA_CHECK_CODE = 0;
    protected static final int RESULT_SPEECH = 1;
    private Bundle bundle;
     
    
 private OnClickListener sendMessageButtonListener=new OnClickListener() {
		
		public void onClick(View v) {
				Intent intent=new Intent(ReplyKeyboardActivity.this,SuccessActivity.class);
				bundle.putCharSequence("message", message.getText().toString());
				intent.putExtras(bundle);
		        startActivity(intent);
			
		}
	};
    private OnClickListener speechToTextButtonListener=new OnClickListener() {
		
		public void onClick(View v) {
			Intent intent = new Intent(
                    RecognizerIntent.ACTION_RECOGNIZE_SPEECH);

            intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, "en-US");

            try {
                startActivityForResult(intent, RESULT_SPEECH);
                EditText message = (EditText) findViewById(R.id.message_text);
                message.setText("");
            } catch (ActivityNotFoundException a) {
                Toast t = Toast.makeText(getApplicationContext(),
                        "Opps! Your device doesn't support Speech to Text",
                        Toast.LENGTH_SHORT);
                t.show();
            }
			
		}
	};
    private OnClickListener quickAnswerButtonListener=new OnClickListener() {
		
		public void onClick(View v) {
			Intent intent=new Intent( ReplyKeyboardActivity.this,ReplyPredefinedActivity.class);
	        startActivity(intent);
		}
	};



	private Button sendMessageButton;
	private Button speechToTextButton;
	private Button quickAnswerButton;
	private EditText message;
    
    
    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
		bundle = this.getIntent().getExtras();
		int id=bundle.getInt("idToLoad");
        // ToDo add your GUI initialization code here 

        setContentView(R.layout.reply_keyboard);
        
        // ziskam promenou z extras (preddefinovane odpovedi)
        Intent intent = getIntent();
        String messageText = (String) intent.getStringExtra("messageTxt");
        message = (EditText) findViewById(R.id.message_text);
        if(messageText == null || messageText.equals("") ){ // pokus neni preddefinovana odpoved zobrazim napovedu - hint
            message.setHint(hintTxt);
        }else{ // pokud mam preddefinovanou odpoved zobrazim ji rovnou v inputu
            message.setText(messageText);
            message.setSelection(messageText.length());
        }
        
        Button sendButton = (Button) findViewById(R.id.sendMessageButton);
        sendButton.setOnClickListener(sendMessageButtonListener);
        Button quickAnswerButton = (Button)findViewById(R.id.quickAnswerButton);
        quickAnswerButton.setOnClickListener(quickAnswerButtonListener);
        Button speechToTextButton = (Button)findViewById(R.id.speechToTextButton);
        speechToTextButton.setOnClickListener(speechToTextButtonListener);
        
        mLibrary = GestureLibraries.fromRawResource(this, R.raw.gestures);
        if (!mLibrary.load()) {
          finish();
        }

        GestureOverlayView gestures = (GestureOverlayView) findViewById(R.id.gestures);
        gestures.addOnGesturePerformedListener(this);
        
        Intent checkIntent = new Intent();
        checkIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
        startActivityForResult(checkIntent, MY_DATA_CHECK_CODE);
    }
    
    public void onGesturePerformed(GestureOverlayView overlay, Gesture gesture) {
 	   ArrayList<Prediction> predictions = mLibrary.recognize(gesture);

 	   if (predictions.size() > 0 && predictions.get(0).score > 1.0) {
 	     String result = predictions.get(0).name;

 	     if ("readSMS".equalsIgnoreCase(result)||"readSMSreverse".equalsIgnoreCase(result)) {
 	    	 if (message!=null && message.length()>0) {
 	    		 tts.speak(message.getText().toString(), TextToSpeech.QUEUE_ADD, null);
 	    	 }

 	     }else if("quickAnswer".equalsIgnoreCase(result)||"quickAnswerReverse".equalsIgnoreCase(result)){
 	    	Intent intent=new Intent( ReplyKeyboardActivity.this,ReplyPredefinedActivity.class);
	        startActivity(intent);
 	     }
 	   }
 	}


 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
     if (requestCode == MY_DATA_CHECK_CODE) {
         if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {
             // success, create the TTS instance
             tts = new TextToSpeech(this, this);
         } 
         else {
             // missing data, install it
             Intent installIntent = new Intent();
             installIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
             startActivity(installIntent);
         }
     }else if(requestCode == RESULT_SPEECH){
    	 if (resultCode == RESULT_OK && null != data) {
             ArrayList<String> text = data
                     .getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);

             message.setText(text.get(0));
         }
    	 
     }

 }
 
 public void onInit(int status) {        
     if (status == TextToSpeech.SUCCESS) {
         //Toast.makeText(MessageActivity.this, 
         //        "Text-To-Speech engine is initialized", Toast.LENGTH_LONG).show();
     }
     else if (status == TextToSpeech.ERROR) {
         Toast.makeText(ReplyKeyboardActivity.this, 
                 "Error occurred while initializing Text-To-Speech engine", Toast.LENGTH_LONG).show();
     }
 }
 
 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
     getMenuInflater().inflate(R.menu.message, menu);
     return true;
 }


    
    //---sends an SMS message to another device---
//    private void sendSMS(String phoneNumber, String message)
//    {        
//        PendingIntent pi = PendingIntent.getActivity(this, 0,
//            new Intent(this, ReplyKeyboardActivity.class), 0);                
//        SmsManager sms = SmsManager.getDefault();
//        sms.sendTextMessage(phoneNumber, null, message, pi, null);        
//    }
    
   
}
